
package com.umeng.community.example;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.qianxx.draw.R;
import com.qianxx.base.BaseAty;
import com.qianxx.base.utils.SPUtil;
import com.umeng.comm.core.CommunitySDK;
import com.umeng.comm.core.beans.CommConfig;
import com.umeng.comm.core.beans.CommUser;
import com.umeng.comm.core.beans.FeedItem;
import com.umeng.comm.core.beans.MessageCount;
import com.umeng.comm.core.beans.Topic;
import com.umeng.comm.core.impl.CommunityFactory;
import com.umeng.comm.core.impl.CommunitySDKImpl;
import com.umeng.comm.core.listeners.Listeners.FetchListener;
import com.umeng.comm.core.login.LoginListener;
import com.umeng.comm.core.login.Loginable;
import com.umeng.comm.core.nets.responses.AlbumResponse;
import com.umeng.comm.core.nets.responses.FeedsResponse;
import com.umeng.comm.core.nets.responses.MessageCountResponse;
import com.umeng.comm.core.nets.responses.TopicResponse;
import com.umeng.comm.core.nets.responses.UsersResponse;
import com.umeng.comm.core.sdkmanager.ImageLoaderManager;
import com.umeng.comm.core.sdkmanager.LocationSDKManager;
import com.umeng.comm.core.sdkmanager.LoginSDKManager;
import com.umeng.comm.core.utils.CommonUtils;
import com.umeng.comm.ui.activities.PostFeedActivity;
import com.umeng.comm.ui.fragments.CommunityMainFragment;
import com.umeng.comm.ui.fragments.FindFragment;
import com.umeng.comm.ui.fragments.NewMsgFragments;
import com.umeng.comm.ui.fragments.PostFeedFragment;
import com.umeng.comm.ui.fragments.UserInfoFragment;
import com.umeng.community.example.Utils.ThirdLoginRequestUtils;
import com.umeng.community.example.Utils.UpgradeManager;
import com.umeng.community.example.custom.SimpleLoginImpl;
import com.umeng.community.example.custom.UILImageLoader;
import com.umeng.community.location.DefaultLocationImpl;
import com.umeng.community.login.UMAuthService;
import com.umeng.community.login.UMLoginServiceFactory;
import com.umeng.community.share.UMShareServiceFactory;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

/**
 * 该类是微社区Demo的主界面Activity类，演示了以Fragment的形式集成友盟微社区。友盟微社区的主页Fragment为
 * {@link CommunityMainFragment},该类继承自v4包中的Fragment。 </p> 该类中还演示了注入自定义登录系统
 * {@link #useCustomLogin()}、配置友盟Social实现的登录系统 {@link #useSocialLogin()}
 * 以及一些常用接口的示例 {@link #someMethodsDemo()}
 */

/**
 * 论坛版微博版只能使用一种ui，当import com.umeng.commm.ui.fragments.CommunityMainFragment时是论坛版式
 * 如果使用微博版式则改为import com.umeng.comm.ui.fragments.CommunityMainFragment;
 * 在AndroidManifest中选择对应appid和appsecret，同时如果选择微博版可以删除论坛版对应注册的activity，同理选择论坛版
 * 可以删除微博版对应注册的activity
 */

public class MainActivity extends BaseAty {

    CommunitySDK mCommSDK = null;
    String topicId = "";

    // 分类文字
    private String[] columns_tv;
    // fragment 的 lab
    private String[] fragmentName;

    // 分类图片
    private int[] columns_img;

    // 各分类片段
    private Class[] fragments;

    // 控制切换的tab
    private FragmentTabHost mTabHost;

    private int currentTab;

    // 未读消息textview
    private TextView unreadLabel;
    /**
     * 未读消息的数量
     */
    private MessageCount mUnreadMsg;

    private boolean tab = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 1、初始化友盟微社区
        mCommSDK = CommunityFactory.getCommSDK(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ==================== 注意 ===================
        // 开发者如果想将友盟微社区作为ViewPager中的一个页面集成到应用中时，请将您的ViewPager替换为CommunityViewPager，
        // 避免滑动时间冲突导致问题
        // CommunityViewPager viewPager = (CommunityViewPager)
        // findViewById(R.id.viewPager);
        // // 设置ViewPager的Adapter
        // viewPager.setAdapter(new
        // FragmentTabAdapter(getSupportFragmentManager()));
        // ===============================================

//        findViewById(R.id.increase).setOnClickListener(new Listeners.LoginOnViewClickListener() {
//            @Override
//            protected void doAfterLogin(View v) {
//                startActivity(new Intent(MainActivity.this, PostFeedActivity.class));
//            }
//        });
//        findViewById(R.id.increase).setOnClickListener(new Listeners.LoginOnViewClickListener() {
//            @Override
//            protected void doAfterLogin(View v) {
////                ThirdLogin(CommConfig.getConfig().loginedUser);
//                ThirdLoginRequestUtils.getInstance(MainActivity.this).ThirdLogin(CommConfig.getConfig().loginedUser);
//
//            }
//        });

        findViewById(R.id.increase).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(SPUtil.getInstance().getToken()) || !CommonUtils.isLogin(MainActivity.this)) {

                    CommunitySDKImpl.getInstance().login(MainActivity.this, new LoginListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onComplete(int stCode, CommUser userInfo) {

                            if (stCode == 0) {
                                showLoading();
                                ThirdLoginRequestUtils.getInstance(MainActivity.this).ThirdLogin(userInfo, new ThirdLoginRequestUtils.HideLoading() {
                                    @Override
                                    public void setHideLoading() {
                                        hideLoading();
                                    }
                                });
                                startActivity(new Intent(MainActivity.this, PostFeedActivity.class));
                            }
                        }
                    });
                } else {
                    startActivity(new Intent(MainActivity.this, PostFeedActivity.class));
                }
            }
        });

        tab = getIntent().getBooleanExtra("tab", false);

        initData();
        initTab();

        if (tab) {
            mTabHost.setCurrentTab(3);
        }

//        // 2、单纯Fragment使用方式
//
//        CommunityMainFragment fragment = new CommunityMainFragment();
//        fragment.setBackButtonVisibility(View.GONE);
//        // 3、将友盟微社区的首页Fragment添加到Activity中
//        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment).commit();

        // =================== 自定义设置部分 =================
        // 在初始化CommunitySDK之前配置推送和登录等组件
        useSocialLogin();

        // 使用自定义的ImageLoader
        // useMyImageLoader();

        // 使用自定义的登录系统
        //useCustomLogin();

        initPlatforms(this);
        // 设置地理位置SDK
        LocationSDKManager.getInstance().addAndUse(new DefaultLocationImpl());
        //TODO
        // 必须有
        UpgradeManager.getInstance().setIsFirst(true);
    }

    // 初始化数据
    private void initData() {
        columns_tv = getResources().getStringArray(R.array.tab_array);
        columns_img = new int[]{R.drawable.tab_square_selector,
                R.drawable.tab_found_selector, R.drawable.fabu_btn,
                R.drawable.tab_info_selector, R.drawable.tab_my_selector};
        fragments = new Class[]{CommunityMainFragment.class, FindFragment.class,
                PostFeedFragment.class, NewMsgFragments.class, UserInfoFragment.class};
        fragmentName = new String[]{"CommunityMainFragment", "FindFragment",
                "PostFeedFragment", "NewMsgFragments", "UserInfoFragment"};
    }

    // 初始化tab
    private void initTab() {
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.setOnTabChangedListener(tabChangeListener);// 绑定监听
        for (int i = 0; i < columns_tv.length; i++) {
            View layout = getLayoutInflater().inflate(R.layout.main_tab_item,
                    null);
            TextView tab_tv = (TextView) layout.findViewById(R.id.tab_name);
            tab_tv.setText(columns_tv[i]);
            if (i == 2) {
                tab_tv.setVisibility(View.GONE);

            }

            if (i == 3) {
                unreadLabel = (TextView) layout.findViewById(R.id.unread_msg_number);
            }
            ImageView tab_img = (ImageView) layout.findViewById(R.id.tab_image);
            tab_img.setImageResource(columns_img[i]);
            if (i == 2) {
                tab_img.setVisibility(View.GONE);
            }
            mTabHost.addTab(
                    mTabHost.newTabSpec(fragmentName[i]).setIndicator(layout),
                    fragments[i], null);
        }
    }

    private int lastTab;
    TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {

            // 上次位置和当前不一样时同步数据

            if (mTabHost.getCurrentTab() != currentTab) {
                lastTab = currentTab;
            }
            currentTab = mTabHost.getCurrentTab();


            if (currentTab == 3 || currentTab == 4) {
                Log.i("ss", "token" + SPUtil.getInstance().getToken() + "" + CommonUtils.isLogin(MainActivity.this));
                if (TextUtils.isEmpty(SPUtil.getInstance().getToken()) || !CommonUtils.isLogin(MainActivity.this)) {

                    CommunitySDKImpl.getInstance().login(MainActivity.this, new LoginListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onComplete(int stCode, CommUser userInfo) {
                            Log.i("ss", "stCode=" + stCode);
                            if (stCode == 0) {
                                CommUser user = CommonUtils.getLoginUser(MainActivity.this);
                                Log.i("ss", user + "");
                                CommConfig.getConfig().loginedUser = CommonUtils.getLoginUser(MainActivity.this);
                                showLoading();
                                ThirdLoginRequestUtils.getInstance(MainActivity.this).ThirdLogin(userInfo, new ThirdLoginRequestUtils.HideLoading() {
                                    @Override
                                    public void setHideLoading() {
                                        hideLoading();
                                    }
                                });
                            }
                        }
                    });
                    mTabHost.setCurrentTab(lastTab);
                }
            }

        }
    };


    public static void actionStart(Context context, boolean tab) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("tab", tab);
        context.startActivity(intent);
    }

    /**
     * 初始化分享相关的平台
     *
     * @param activity
     */
    private void initPlatforms(Activity activity) {
        // 添加QQ
        UMQQSsoHandler qqHandler = new UMQQSsoHandler(activity, "1105302197",
                "74TMGWsdcKjeOGAA");
        qqHandler.addToSocialSDK();
        // 添加QZone平台
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(activity, "1105302197",
                "74TMGWsdcKjeOGAA");
        qZoneSsoHandler.addToSocialSDK();
        // 添加微信平台
        UMWXHandler wechatHandler = new UMWXHandler(activity, "wxc61cc9fa9916d7af",
                "18e2b42ba52c444f96e9bdb5a667ad97");
        wechatHandler.addToSocialSDK();
        // 添加微信朋友圈平台
        UMWXHandler circleHandler = new UMWXHandler(activity, "wxc61cc9fa9916d7af",
                "18e2b42ba52c444f96e9bdb5a667ad97");
        circleHandler.setToCircle(true);
        circleHandler.addToSocialSDK();

        UMShareServiceFactory.getSocialService().getConfig()
                .setPlatforms(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN,
                        SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA);
        UMShareServiceFactory.getSocialService().getConfig()
                .setPlatformOrder(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN,
                        SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA);
    }

    /**
     * 自定义自己的登录系统
     */
    protected void useSocialLogin() {

        // 用户自定义的登录
        UMAuthService mLogin = UMLoginServiceFactory.getLoginService("umeng_login_impl");
        String appId = "1105302197";
        String appKey = "74TMGWsdcKjeOGAA";
        // SSO 设置
        // mLogin.getConfig().setSsoHandler(new SinaSsoHandler());
        new UMQQSsoHandler(this, appId, appKey).addToSocialSDK();

        String wxappId = "wxc61cc9fa9916d7af";
        String wxappSecret = "18e2b42ba52c444f96e9bdb5a667ad97";
        new UMWXHandler(getApplicationContext(), wxappId,
                wxappSecret).addToSocialSDK();

        // 将登录实现注入到sdk中,key为umeng_login
        LoginSDKManager.getInstance().addAndUse(mLogin);

    }

    protected void useCustomLogin() {
        // 管理器
        LoginSDKManager.getInstance().addAndUse(new SimpleLoginImpl());
    }

    /**
     * 自定义自己的ImageLoader
     */
    protected void useMyImageLoader() {
        //
        final String imageLoadKey = UILImageLoader.class.getSimpleName();
        // 使用第三方ImageLoader库,添加到sdk manager中, 并且使用useThis来使用该加载器.
        ImageLoaderManager manager = ImageLoaderManager.getInstance();
        manager.addImpl(imageLoadKey, new UILImageLoader(this));
        manager.useThis(imageLoadKey);
    }

    /**
     * 一些常用的接口以及获取推荐的数据接口
     */
    void someMethodsDemo() {
        // 主动登录
        mCommSDK.login(getApplicationContext(), new LoginListener() {

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(int stCode, CommUser userInfo) {

            }
        });

        // 获取登录SDK Manager
        LoginSDKManager manager = LoginSDKManager.getInstance();
        Loginable currentLoginable = manager.getCurrentSDK();
        // 是否登录
        //currentLoginable.isLogined(getApplicationContext());

        // 未登录下获取话题
        mCommSDK.fetchTopics(new FetchListener<TopicResponse>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(TopicResponse response) {
                for (Topic item : response.result) {
                    Log.e("", "### topic id : " + item.id + ", name = " + item.name);
                    topicId = item.id;
                }

            }
        });

        // 未登录情况下获取某个话题下的feed
        mCommSDK.fetchTopicFeed(topicId, new
                FetchListener<FeedsResponse>() {

                    @Override
                    public void onComplete(FeedsResponse response) {
                        Log.e("", "### 未登录下获取到某个topic下的feed : " + response.result.size());
                        for (FeedItem item : response.result) {
                            Log.e("", "### topic feed id : " + item.id + ", name = " +
                                    item.text);
                        }

                    }

                    @Override
                    public void onStart() {
                    }
                });

        // 推荐的feed
        mCommSDK.fetchRecommendedFeeds(new FetchListener<FeedsResponse>() {

            @Override
            public void onComplete(FeedsResponse response) {
                Log.e("", "### 推荐feed  code : " + response.errCode + ", msg = " + response.errMsg);
                for (FeedItem item : response.result) {
                    Log.e("", "### 推荐feed id : " + item.id + ", name = " + item.text);
                }
            }

            @Override
            public void onStart() {

            }
        });

        // 获取推荐的话题
        mCommSDK.fetchRecommendedTopics(new FetchListener<TopicResponse>() {

            @Override
            public void onComplete(TopicResponse response) {
                Log.e("", "### 推荐的话题 : ");
                for (Topic item : response.result) {
                    Log.e("", "### 话题 : " + item.name);
                }
            }

            @Override
            public void onStart() {

            }
        });

        // 获取某个话题活跃的用户
        mCommSDK.fetchActiveUsers("541fe6f40bbbaf4f41f7aa3f", new FetchListener<UsersResponse>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(UsersResponse response) {
                Log.e("", "### 某个话题的活跃用户 : ");
                for (CommUser user : response.result) {
                    Log.e("", "### 活跃用户 : " + user.name);
                }
            }
        });

        // 获取某用户的相册,也就是发布feed上传的所有图片
        mCommSDK.fetchAlbums(CommConfig.getConfig().loginedUser.id,
                new FetchListener<AlbumResponse>() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(AlbumResponse response) {
                        Log.e("", "### response size : " + response.result.size());
                    }
                });

        // 搜索周边的feed
        mCommSDK.searchFeedNearby(116.3758540000f, 39.9856970000f,
                new FetchListener<FeedsResponse>() {

                    @Override
                    public void onComplete(FeedsResponse response) {
                        Log.e("", "### 周边的feed : " + response.result.size());
                    }

                    @Override
                    public void onStart() {

                    }

                });

//        mCommSDK.fetchUnReadMessageCount(new FetchListener<MessageCountResponse>(){
//
//        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //TODO
        // 检测版本更新
        UpgradeManager.getInstance().checkUpgrade(this);
        Log.i("ss", SPUtil.getInstance().getToken() + "," + CommonUtils.isLogin(MainActivity.this));
        if ((TextUtils.isEmpty(SPUtil.getInstance().getToken()) ||
                !CommonUtils.isLogin(MainActivity.this)) && currentTab == 4) {
            currentTab = 0;
            mTabHost.setCurrentTab(currentTab);
        }
        setUnread(); // 设置未读消息数量
    }

    private void setUnread() {
        MessageCount mUnreadMsg = CommConfig.getConfig().mMessageCount;
//        printUnread(mUnreadMsg); // 临时，打印未读消息
        if (TextUtils.isEmpty(SPUtil.getInstance().getToken()) ||
                !CommonUtils.isLogin(MainActivity.this)) {
            unreadLabel.setVisibility(View.GONE);
        } else {
            if (mUnreadMsg != null && mUnreadMsg.unReadTotal > 0) {
                unreadLabel.setVisibility(View.VISIBLE);
                int totalUnread = getUnread(mUnreadMsg);
                String num = totalUnread >= 100 ? "..." : totalUnread + "";
                unreadLabel.setText(num);
            } else {
                unreadLabel.setVisibility(View.GONE);
            }
        }
    }

//    // 打印未读消息
//    private void printUnread(MessageCount mUnreadMsg) {
//        if (mUnreadMsg == null) {
//            return;
//        }
//        LogUtil.e("----- unReadSessionsCount = " + mUnreadMsg.unReadSessionsCount);
//        LogUtil.e("----- unReadLikesCount = " + mUnreadMsg.unReadLikesCount);
//        LogUtil.e("----- unReadNotice = " + mUnreadMsg.unReadNotice);
//        LogUtil.e("----- unReadCommentsCount = " + mUnreadMsg.unReadCommentsCount);
//        LogUtil.e("----- unReadAtCount = " + mUnreadMsg.unReadAtCount);
//        LogUtil.e("----- unReadTotal = " + mUnreadMsg.unReadTotal);
//    }

    // 获取总的未读消息数

    private int getUnread(MessageCount mUnreadMsg) {
        int totalUnread = 0;
        totalUnread = mUnreadMsg.unReadCommentsCount + mUnreadMsg.unReadLikesCount
                + mUnreadMsg.unReadAtCount + mUnreadMsg.unReadNotice;
        return totalUnread;
    }

}
